<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
      <tips optionTemplate="noticeList"></tips>
      <div class="toplineBox mb-10">
        <div class="toplineBox-left">
          <el-input v-model="searchWord" placeholder="填写通知标题" size="small" class="w-200 mr-10"></el-input>
          <el-date-picker
              v-model="searchYear"
              type="year"
              size="small"
              class="mr-10"
              value-format="yyyy"
              placeholder="选择年">
          </el-date-picker>
          <el-button type="primary" size="small" @click="searchFn"><i class="el-icon-search"></i>搜索</el-button>
          <el-button size="small" @click="refreshFn"><i class="el-icon-refresh"></i>刷新</el-button>
          <el-button @click="downexcel" size="small" class="mr-10">电子通知导出Excel</el-button>
        </div>
        <p class="numberline toplineBox-right">总{{ page.total }}条</p>
      </div>
      <!--本体列表，数据 -->
      <div class="table-body">
        <div class="table-body-box">
          <el-table
              ref="multipleTable"
              :data="arryList"
              :stripe="tableStyle.tableStripe"
              :border="tableStyle.tableBorder"
              tooltip-effect="dark"
              style="width: 100%"
              header-cell-class-name="table-text-c"
              cell-class-name="table-text-c">
            <el-table-column
                prop="title"
                label="通知标题">
            </el-table-column>
            <el-table-column
                label="发布人">
              <template slot-scope="scope">
                <span v-if="scope.row.user">{{ scope.row.user.realname }}</span>
                <span v-else class="c-danger">未知/或已删除</span>
              </template>
            </el-table-column>
            <el-table-column
                label="审核人">
              <template slot-scope="scope">
                <span v-if="scope.row.examine">{{ scope.row.examine.realname }}</span>
                <span v-else class="c-danger">未知/或已删除</span>
              </template>
            </el-table-column>
            <el-table-column
                label="通知范围">
              <template slot-scope="scope">
                <span v-if="scope.row.type==0">全校</span>
                <span v-if="scope.row.type==1">特定年段(<span v-for="(item,index) in scope.row.section_id"
                                                          :key="index">{{ item.section_name }}</span>)</span>
                <span v-if="scope.row.type==2">特定班级(<span v-for="(item,index) in scope.row.class_id"
                                                          :key="index">{{ item.class_name }}</span>)</span>
              </template>
            </el-table-column>
            <el-table-column
                label="通知人数"
                prop="count">
            </el-table-column>
            <el-table-column
                prop="read_number"
                label="已签收人数">
              <template slot-scope="scope">
                <!--<span @click="checkUserList(scope.$index,1)" class="geiUser">{{scope.row.read_number}}</span>-->
                <!--                <el-button size="small" @click="detelTearch(scope.row.id)">{{scope.row.read_number}}</el-button>-->
                <el-button size="small" @click="noticeId=scope.row.id,listType=1,signForVisible=true">
                  {{ scope.row.read_number }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
                label="未签收人数">
              <template slot-scope="scope">
                <el-button size="small" @click="noticeId=scope.row.id,listType=2,signForVisible=true"
                           v-if="scope.row.is_unread">{{ scope.row.count - scope.row.read_number }}
                </el-button>
                <el-button size="small" v-else @click="timeloseFn">
                  {{ scope.row.count - scope.row.read_number }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
                prop="create_time"
                label="发布时间">
            </el-table-column>
            <el-table-column
                prop="time"
                label="要求送达时间">
              <template slot-scope="scope">
                <p class="timeline" @click="showEditTime(scope.row)">{{ scope.row.time }}</p>
              </template>
            </el-table-column>
            <el-table-column
                label="操作"
                width="140">
              <template slot-scope="scope">
                <el-dropdown @command="handleCommand" trigger="click">
                  <el-button type="primary" size="mini">
                    更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="1+'-'+scope.$index">通知详情</el-dropdown-item>
                    <el-dropdown-item :command="2+'-'+scope.$index" v-if="scope.row.showQrcode">生成二维码</el-dropdown-item>
                    <!--                    <el-dropdown-item :command="3+'-'+scope.$index">签名详情</el-dropdown-item>-->
                    <el-dropdown-item :command="4+'-'+scope.$index" v-if="userInfo && userInfo.id==1">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!--工具条 分页-->
      <el-col :span="24" class="toolbar">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="page.total"
            :page-size="page.pagesize"
            @current-change="handleSizeChange">
        </el-pagination>
      </el-col>
      <applycode :visible.sync="qrcodeVisible" :codetype="codetype" :listId="listId"></applycode>
      <signFor :visible.sync="signForVisible" :noticeId="noticeId" :listType="listType" @InitFn="InitFn"></signFor>
    </div>
    <noticeDetail :visible.sync="detailVisible" :detailId="detailId"></noticeDetail>
    <editTime :visible.sync="editTimeVisible" :questionData="questionData" typeline="3" @InitFn="InitFn"></editTime>
  </div>
</template>

<script>
import applycode from '@/components/dialog/applycode.vue'
import {pagination, tableoption} from '@/utils/util.js'
import api from '@/utils/api.js'
import {mapGetters, mapActions} from "vuex";
import signFor from "./components/Sign-for"
import noticeDetail from "./components/noticeDetail";
import editTime from "../questionnaire/components/editTime";

export default {
  components: {
    applycode,
    signFor,
    noticeDetail,
    editTime
  },
  data() {
    return {
      detailVisible: false,
      detailId: 0,
      codetype: 1, // 1 通知 2 问卷
      signForVisible: false,
      noticeId: 0,
      listType: 0,
      handleSelection: [],
      qrcodeVisible: false,
      arryList: [], // 页面数据列表
      // 搜索设置
      searchWord: '', // 搜索名称
      // 设置table样式
      tableStyle: tableoption,
      // 设置table页面分页所需
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      listId: '',
      searchYear: '',
      questionData: null,
      editTimeVisible: false
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  created() {
    this.InitFn()
  },
  methods: {
    // 初始化
    InitFn() {
      // 0待审核1审核2驳回 is_examine
      this.$fetch(api.admin_notice_index, {
        p: this.page.pageindex,
        title: this.searchWord,
        year: this.searchYear,
        is_examine: 1
      }).then((response) => {
        if (response.code === 0) {
          let array_ = []
          console.log('userInfo:', this.userInfo)
          for (let item of response.list.data) {
            if (Number(this.userInfo.type) === 0 || Number(this.userInfo.type) === 1) {
              item.showQrcode = false
              if (item.type === 1) {
                // 匹配年段
                // if (this.userInfo.section_id === item.section_id[0].id) {
                //   item.showQrcode = true
                // }
                for (let itemSection of item.section_id) {
                  if (this.userInfo.section_id === itemSection.id) {
                    item.showQrcode = true
                  }
                }
              } else if (item.type === 2) {
                // 匹配班级
                for (let class_ of item.class_id) {
                  if (this.userInfo.class_id === class_.id) {
                    item.showQrcode = true
                  }
                }
              } else {
                item.showQrcode = true
              }
            }
            item.create_time = item.create_time.split(' ')[0]
            item.time = item.time.split(' ')[0]
          }
          this.arryList = response.list.data
          this.page.total = response.list.total
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    searchFn() {
      this.page.pageindex = 1
      this.InitFn()
    },
    getqrcode(index) {
      this.listId = this.arryList[index].id
      // this.qrcodeSrc = this.arryList[index].qr_code
      this.qrcodeVisible = true
    },
    checkIdCard(option) {
      this.editId = option || ''
      this.addclassVisible = true
    },
    handleSelectionChange(val) {
      this.handleSelection = val
    },
    timeloseFn() {
      this.$message.warning('过期数据')
    },
    // 分页
    handleSizeChange(val) {
      this.page.pageindex = val
      this.InitFn()
    },
    // 刷新页面
    refreshFn() {
      this.searchWord = '';
      this.searchYear = '';
      this.page.pageindex = 1
      this.InitFn()
    },
    gotoDetail(id) {
      this.$router.push('NoticeDetail?editId=' + id)
    },
    handleDetel(index) {
      this.$confirm('确认永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.detelRespon(index)
      }).catch(() => {
      })
    },
    detelRespon(index) {
      this.$post(api.admin_notice_delete, {id: this.arryList[index].id}).then((response) => {
        if (response.code === 0) {
          this.arryList.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    downexcel() {
      // book/export
      console.log('下载')
      this.$http({
        method: 'get',
        url: `${this.$BASE_URL}/admin/${this.api.notice_export}`,
        responseType: 'arraybuffer'
      })
          .then(
              function (response) {
                let filename = '电子通知资料.xlsx'
                this.fileDownload(response.data, filename)
              }.bind(this)
          )
          .catch(
              function (error) {
                alert('网络请求出错')
              }
          )
    },
    fileDownload(data, fileName) {
      let blob = new Blob([data], {
        type: 'application/octet-stream'
      })
      let filename = fileName || 'filename.xls'
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
      } else {
        let blobURL = window.URL.createObjectURL(blob)
        let tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      }
    },
    handleCommand(command) {
      let command_ = command.split('-')
      let n = this;
      if (Number(command_[0]) === 1) {
        // this.gotoDetail(this.arryList[command_[1]].id)
        this.detailId = this.arryList[command_[1]].id;
        this.detailVisible = true;
      }
      // 视频采集
      if (Number(command_[0]) === 2) {
        this.getqrcode(command_[1])
      }
      // 视频记录
      if (Number(command_[0]) === 3) {
        this.detelTearch(this.arryList[command_[1]].id)
      }
      if (Number(command_[0]) === 4) {
        this.handleDetel(command_[1])
      }
    },
    showEditTime(row){
      this.questionData = JSON.parse(JSON.stringify({
        id: row.id,
        time: row.time.split(' ')[0],
      }))
      this.editTimeVisible = true
    }
  },
  mounted() {
  },
  // 缓存机制 star
  beforeRouteEnter(to, from, next) {
    // 利用路由元信息中的 meta 字段设置变量，方便在各个位置获取。这就是为什么在 meta 中定义 isNeedRefresh。
    // 当从详情页返回时，将 isNeedRefresh 设为 false，表示不刷新数据
    if (to.meta.isNeedRefresh) {
      this.InitFn() // 详情页面需要刷新数据
    }
    next()
  },
  beforeRouteLeave(to, from, next) {
    // isNeedRefresh 进入页面判断是否需要刷新
    if (to.meta.isNeedRefresh) {
      from.meta.keepAlive = true
    } else {
      from.meta.keepAlive = false
    }
    next()
  }

  // 缓存机制 end
}
</script>
<style>
.timeline:hover {
  text-decoration: underline;
  color: #006dcd;
}
</style>
